package com.example.springbootexamples;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

public class Run implements Runnable{
    ThreadPoolExecutor threadPoolExecutor;
    static RestTemplate restTemplate=new RestTemplate();
    AtomicInteger total;
    AtomicInteger success;
    AtomicInteger fail;
    Map<String, List<Long>> map;
    public Run(ThreadPoolExecutor threadPoolExecutor, AtomicInteger total, AtomicInteger success, AtomicInteger fail,Map<String, List<Long>> map) {
        this.threadPoolExecutor = threadPoolExecutor;
        this.total = total;
        this.success = success;
        this.fail = fail;
        this.map=map;
    }
    @Override
    public void run() {
        List<Long> list=map.get(Thread.currentThread().getName());
        if(list==null){
            list=new ArrayList<>();
            map.put(Thread.currentThread().getName(),list);
        }

        total.incrementAndGet();
        String body="";
        long t=System.currentTimeMillis();
        try {
            String s = restTemplate.postForObject("http://localhost:8081/test/t", body, String.class);
            JSONObject r=JSONObject.parseObject(s);
            //System.out.println(r);
            if ("1".equals(r.getString("code"))) {
                success.incrementAndGet();
                list.add(System.currentTimeMillis() - t);
            } else {
                fail.incrementAndGet();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
